// pages/addCard/addCard.js
var util = require('../../utils/request.js');
var globalData = getApp().globalData;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: '0',
    showKeyBoard: true,
    showHanzi: true,
    inputText1: [],
    inputText2: [],
    modify: 'add',
    cardMessage: '',
    activeKey: 'false',
    hanziList: ['京', '沪', '粤', '津', '浙', '苏', '湘', '渝', '云', '豫', '皖', '陕', '桂', '新', '青', '琼', '闽', '蒙', '辽', '宁', '鲁', '晋', '吉', '冀', '黑', '甘', '鄂', '赣', '贵', '川', '藏', '民'],
    letterKey: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
    // 临时停车提示
    showSearch: true
  },
  //查找车牌缴费信息
  search: function (id) {
    console.log(id)
    var that = this
    util.req('/order/refreshParkingOrder', { number: id }, function (success) {
      console.log(success)
      if (success.resultCode == 200) {
        var orderInfo = {
          finishDate: util.formatTime(success.resultContent.finishDate),
          orderDuration: util.formatSeconds(success.resultContent.orderDuration),
          business: success.resultContent.business,
          useDate: util.formatTime(success.resultContent.useDate),
          card: success.resultContent.number,
          cardType: that.data.current == '0' ? 'ordinary' : 'energy',
          amount: Math.floor(success.resultContent.amount * 100) / 100,
          parkType: success.resultContent.parkType,
          sn: success.resultContent.sn
        }
        wx.setStorage({
          key: 'cardMessage',
          data: orderInfo,
          success: function() {
            wx.navigateTo({
              url: '../zdPark_search/zdPark_search',
            })
          }
        })
      } else {
        wx.showToast({
          title: success.resultMsg,
          icon: 'none'
        })
      }
    })
  },
  // 切换添加/查找按钮
  search_card() {
    this.finish('search');
  },
  // 点击页面吗，关闭键盘
  container() {
    this.setData({
      showKeyBoard: false
    })
  },
  // 点击切换普通牌
  selectCommon() {
    if (this.data.modify == 'modify') {
      this.setData({
        current: this.data.current
      })
    } else {
      this.setData({
        current: '0',
        showKeyBoard: true,
        showHanzi: true,
        inputText1: [],
        inputText2: []
      })
    }
  },
  // 点击切换新能源
  selectEnergy() {
    if (this.data.modify == 'modify') {
      this.setData({
        current: this.data.current
      })
    } else {
      this.setData({
        current: '1',
        showKeyBoard: true,
        showHanzi: true,
        inputText1: [],
        inputText2: []
      })
    }
  },
  // 滑动
  changeSelect: function (e) {
    if (this.data.modify == 'modify') {
      this.setData({
        current: this.data.current
      })
    } else {
      this.setData({
        current: e.detail.current,
        showKeyBoard: true,
        showHanzi: true,
        inputText1: [],
        inputText2: [],
      })
    }
  },
  // 点击汉字键盘
  getHanzi(e) {
    console.log(e);
    if (this.data.current == 0) {
      var text = this.data.inputText1;
      text.push(e.currentTarget.id);
      console.log(e.currentTarget.id,text);
      this.setData({
        inputText1: text,
        showHanzi: false
      })
      console.log(this.data.inputText1);
    } else if (this.data.current == 1) {
      var text = this.data.inputText2;
      text.push(e.currentTarget.id);
      console.log(e.currentTarget.id, text);
      this.setData({
        inputText2: text,
        showHanzi: false
      })
      console.log(this.data.inputText2);
    }
  },
  // 点击字母和数字键盘
  getLetter(e) {
    if (this.data.current == 0) {
      var text = this.data.inputText1;
      if (text.length < 7) {
        text.push(e.currentTarget.id);
      }
      this.setData({
        inputText1: text
      })
    } else if (this.data.current == 1) {
      var text = this.data.inputText2;
      if (text.length < 8) {
        text.push(e.currentTarget.id);
      }
      this.setData({
        inputText2: text
      })
    }
  },
  // 清空
  clear() {
    if (this.data.current == 0) {
      this.setData({
        inputText1: [],
        showHanzi: true,
      })
    } else {
      this.setData({
        inputText2: [],
        showHanzi: true,
      })
    }
  },
  // 删除
  delete() {
    if (this.data.current == 0) {
      var text = this.data.inputText1;
      text.pop();
      console.log(text);
      if (text.length <= 0) {
        this.setData({
          inputText1: text,
          showHanzi: true,
        })
      } else {
        this.setData({
          inputText1: text
        })
      }
    } else {
      var text = this.data.inputText2;
      text.pop();
      console.log(text);
      if (text.length <= 0) {
        this.setData({
          inputText2: text,
          showHanzi: true,
        })
      } else {
        this.setData({
          inputText2: text
        })
      }
    }
  },
  // 弹出车牌键盘
  showKeyBoard() {
    console.log('show');
    this.setData({
      showKeyBoard: !this.data.showKeyBoard
    })
  },
  // 获取输入的普通车牌
  getCode1(e) {
    console.log(e);
    if (this.data.inputText1 != '' && e.detail.value == '' && this.data.inputText1.length != 1) {

    } else {
      this.setData({
        inputText1: e.detail.value.split('')
      })
    }
    console.log(this.data.inputText1);
  },
  // 获取输入的新能源车牌
  getCode2(e) {
    console.log(e);
    if (this.data.inputText2 != '' && e.detail.value == '' && this.data.inputText2.length != 1) {

    } else {
      this.setData({
        inputText2: e.detail.value.split('')
      })
    }
  },
  // 点击完成
  finish: function (e) {
    e = e || 'other';
    if (this.data.current == 0) {
      // 普通车牌
      var id = this.data.inputText1.join('');
      console.log(id);
      var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
      var result = express.test(id);
      
      if (id.length == 7 && result) {
        if(e == 'search') {
          this.search(id);
        } else {
          this.addCard('ordinary', id);
        }
      } else {
        wx.showToast({
          title: '车牌格式不正确',
          icon: 'none'
        })
      }

    } else {
      // 新能源车牌
      var id = this.data.inputText2.join('');
      console.log(id,id.length);
      var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF][A-HJ-NP-Z0-9][0-9]{4}))$/;
      var result = express.test(id);
      if (id.length == 8 && result) {
        if (e == 'search') {
          this.search(id);
        } else {
          this.addCard('energy', id);
        }
      } else {
        wx.showToast({
          title: '车牌格式不正确',
          icon: 'none'
        })
      }
    }
  },
  // 添加车牌
  addCard(cardType, id) {
    var that = this;
    var data;
    var url;
    // 判断修改or添加
    if (this.data.modify == 'modify') {
      // 修改
      data = {
        'memberId': globalData.memberId,
        'type': cardType,
        'number': id,
        'id': this.data.cardMessage.licensePlateId
      }
      url = '/licensePlate/updateLicensePlate'
    } else {
      // 添加
      data = {
        'memberId': globalData.memberId,
        'type': cardType,
        'number': id
      }
      url = '/licensePlate/addLicensePlate';
    }

    util.req(url, data, function (res) {
      console.log(res);
      if (res.resultCode == 200) {
        // if (that.data.modify == 'modify') {
        //   wx.showToast({
        //     title: '修改成功'
        //   })
        // } else {
        //   wx.showToast({
        //     title: '添加成功'
        //   })
        // }
        wx.showToast({
          title: res.resultMsg,
        })
        setTimeout(function () {
          wx.redirectTo({
            url: '../plateNumList/plateNumList',
          })
        }, 500)
      } else if(res.resultCode == 300) {
        wx.showModal({
          title: '提示',
          content: res.resultMsg,
          success: function(tip) {
            console.log(tip);
            if(tip.confirm) {
              // that.search(id);
              wx.navigateTo({
                url: '../order/order?to=2',
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: res.resultMsg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 检查是否授权用户信息
    var userInfo = wx.getStorageSync('XPuserInfo');
    if (userInfo == '') {
      wx.redirectTo({
        url: '../authorization/authorization?source=addCard',
      })
    } else{
      //判断有没有绑定手机号
      // 检查一下是否登录，登录后在获取未完成订单
      var timer = setInterval(() => {
        if (globalData.userInfo != null) {
          if (globalData.userInfo.isPhone == null) {
            wx.redirectTo({
              url: '../loginByTel/loginByTel?source=addCard',
            })
          } else {
            console.log(options);
            if (options.number != undefined) {
              var cardMessage = {
                number: options.number,
                licensePlateId: options.licensePlateId,
                type: options.type
              };
              this.setData({
                cardMessage: cardMessage,
                modify: 'modify'
              })
              console.log(options.number);
              if (options.type == 'energy') {
                that.setData({
                  current: '1',
                  showHanzi: false,
                  inputText2: options.number.split('')
                })
              } else {
                that.setData({
                  current: '0',
                  showHanzi: false,
                  inputText1: options.number.split('')
                })
              }
              wx.setNavigationBarTitle({
                title: '修改车牌',
              })
            } else {
              this.setData({
                modify: 'add'
              })
            }
          }
          clearInterval(timer);
        }
      }, 500)
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})